﻿/* =============================================
 * 名    称：JsonLib
 * 功能描述：JsonLib
 * 作    者：yanwei.yang
 * 添加时间：2015/4/14 14:55:36
 * =============================================*/


using fastJSON;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Script.Serialization;


namespace Summer.WeiXin.Utility
{
    public class JsonLib
    {
        /// <summary>
        /// 将对象转换为json字符串
        /// </summary>
        /// <param name="o">对象</param>
        /// <returns>xml格式字符串</returns>
        public static string ConvertToJson(object o)
        {
            JavaScriptSerializer serializer = new JavaScriptSerializer();
            return serializer.Serialize(o);
        }

        /// <summary>
        /// 格式化字符型、日期型、布尔型
        /// </summary>
        /// <param name="str">要格式化的值</param>
        /// <param name="type">要格式化的类型</param>
        /// <returns></returns>
        private static string StringFormat(string str, Type type)
        {

            if (type != typeof(string) && string.IsNullOrEmpty(str))
            {
                str = "\"" + str + "\"";
            }
            else if (type == typeof(string))
            {
                str = String2Json(str);
                str = "\"" + str + "\"";
            }
            else if (type == typeof(DateTime))
            {
                str = "\"" + str.Split(' ')[0] + "\"";
            }
            else if (type == typeof(bool))
            {
                str = str.ToLower();
            }
            return str;
        }


        /// <summary>
        /// string转json
        /// </summary>
        /// <param name="s">要转换的string</param>
        /// <returns></returns>
        private static string String2Json(string s)
        {
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < s.Length; i++)
            {
                char c = s.ToCharArray()[i];
                switch (c)
                {
                    case '\"':
                        sb.Append("\\\""); break;
                    case '\\':
                        sb.Append("\\\\"); break;
                    case '/':
                        sb.Append("\\/"); break;
                    case '\b':
                        sb.Append("\\b"); break;
                    case '\f':
                        sb.Append("\\f"); break;
                    case '\n':
                        sb.Append("\\n"); break;
                    case '\r':
                        sb.Append("\\r"); break;
                    case '\t':
                        sb.Append("\\t"); break;
                    default:
                        sb.Append(c); break;
                }
            }
            return sb.ToString();

        }

        /// <summary>
        /// json转对象
        /// </summary>
        /// <typeparam name="T">对象类型</typeparam>
        /// <param name="jsonText">要转换的json字符串</param>
        /// <returns></returns>
        public static T JsonToObject<T>(string jsonText)
        {
            JavaScriptSerializer jss = new JavaScriptSerializer();
            try
            {
                return jss.Deserialize<T>(jsonText);
            }
            catch (Exception ex)
            {
                throw new Exception("JSONHelper.JSONToObject(): :" + ex.Message);
            }
        }

        /// <summary> 
        /// 将JSON文本转换为数据表数据 
        /// </summary> 
        /// <param name="jsonText">JSON文本</param> 
        /// <returns>数据表字典</returns> 
        public static Dictionary<string, List<Dictionary<string, object>>> TablesDataFromJson(string jsonText)
        {
            return JsonToObject<Dictionary<string, List<Dictionary<string, object>>>>(jsonText);
        }
        /// <summary> 
        /// 将JSON文本转换成数据行 
        /// </summary> 
        /// <param name="jsonText">JSON文本</param> 
        /// <returns>数据行的字典</returns> 
        public static Dictionary<string, object> DataRowFromJson(string jsonText)
        {
            return JsonToObject<Dictionary<string, object>>(jsonText);
        }

        public static readonly JSONParameters jsonp = new JSONParameters() { EnableAnonymousTypes = true, SerializeNullValues = true, UseEscapedUnicode = false, UseExtensions = false, UseFastGuid = false, UseOptimizedDatasetSchema = false, UseUTCDateTime = false, UsingGlobalTypes = true };

        /// <summary>
        /// 使用fastjson序列化object->string
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static string FastToString(object obj)
        {
            return JSON.Instance.ToJSON(obj, jsonp);
        }


        /// <summary>
        /// 使用fastjson反序列化string->object
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="jsonString"></param>
        /// <returns></returns>
        public static T FastToObject<T>(string jsonString)
        {
            return JSON.Instance.ToObject<T>(jsonString);
        }
    }
}
